# encoding: utf-8
import sys
from time import sleep
from multiprocessing import Pool
import io
from sql_ac.sql_1 import insert_merberid, select_all, update_merberid
import json
import threading
from multiprocessing import Queue
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
sys.setrecursionlimit(1000000)
chrome_options = webdriver.ChromeOptions()
# 设置浏览器初始 位置x,y & 宽高x,y
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument(f'--window-position={217},{92}')
chrome_options.add_argument(f'--window-size={1222},{816}')
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
# chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
chrome_options.add_argument('–headless')
desired_capabilities = DesiredCapabilities.CHROME  # 修改页面加载策略
desired_capabilities["pageLoadStrategy"] = "none"
driver = webdriver.Chrome(options=chrome_options)
# with open('stealth.min.js') as f:
#     js = f.read()
# driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
#   "source": js
# })
driver.set_page_load_timeout(10)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})
wait = WebDriverWait(driver, 20)


def login(n, m):
    try:
        iframe = driver.find_element_by_tag_name('iframe')
        driver.switch_to.frame(iframe)
    except:
        pass
    try:
        name = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#fm-login-id')))
        price = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#fm-login-password')))
        prices = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.fm-btn')))
    finally:
        pass
    name.send_keys(n)
    price.send_keys(m)
    prices.click()


def selenium_hw():
    driver.get(
        "https://shop1715c233h75t4.1688.com/page/creditdetail.htm")
    # print(s,'weqeee')
    login('', '')

    data()
    for i in select_all('date_no'):
        with open('damai_cookies.txt', 'r', encoding='utf8') as f:
            listCookies = json.loads(f.read())
        for cookie in listCookies:
            cookie_dict = {
                'domain': '.1688.com',
                'name': cookie.get('name'),
                'value': cookie.get('value'),
                'path': '/',
                "expires": '',
                'sameSite': 'None',
                'secure': cookie.get('secure')
            }
            driver.add_cookie(cookie_dict)
        driver.get(i[3])
        data()



def data():
    try:
        name3 = wait.until(EC.presence_of_element_located((By.XPATH, "//span[@class='name-text']")))
        name1 = wait.until(EC.presence_of_element_located((By.XPATH, "//span[@class='contact-info']")))
        name2 = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='text company-contact']")))
        name4 = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='info-box info-right']")))
    finally:
        pass
    try:
        name = driver.find_element_by_xpath("//span[@class='name-text']").text
    except:
        return data1()
    namer = driver.find_element_by_xpath("//span[@class='contact-info']").text
    phones = driver.find_elements_by_xpath("//span[@class='tip-info phone-num']")
    jyfw = driver.find_element_by_xpath("//p[contains(text(), '经营范围')]/../following-sibling::td/p/span").text
    address = driver.find_element_by_xpath("//p[contains(text(), '注册地址')]/../following-sibling::td/p/span").text
    if len(phones) > 1:
        gh = phones[0].get_attribute('textContent')
        phone = phones[1].get_attribute('textContent')
    elif len(phones) == 1:
        gh = phones[0].get_attribute('textContent')
        phone = ''
    else:
        return ''
    print(name,namer,jyfw,address,phone,gh)
    print('===='*40)
    dictCookies = driver.get_cookies()  # 获取list的cookies
    jsonCookies = json.dumps(dictCookies)  # 转换成字符串保存
    with open('damai_cookies.txt', 'w') as f:
        f.write(jsonCookies)


def data1():
    try:
        name3 = wait.until(EC.presence_of_element_located((By.XPATH, "//span[@class='name-text']")))
        name1 = wait.until(EC.presence_of_element_located((By.XPATH, "//span[@class='contact-info']")))
        name2 = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='text company-contact']")))
        name4 = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='info-box info-right']")))
    finally:
        pass
    name = driver.find_element_by_xpath("//span[@class='name-text']").text
    namer = driver.find_element_by_xpath("//span[@class='contact-info']").text
    phones = driver.find_elements_by_xpath("//span[@class='tip-info phone-num']")
    jyfw = driver.find_element_by_xpath("//p[contains(text(), '经营范围')]/../following-sibling::td/p/span").text
    address = driver.find_element_by_xpath("//p[contains(text(), '注册地址')]/../following-sibling::td/p/span").text
    if len(phones) > 1:
        gh = phones[0].get_attribute('textContent')
        phone = phones[1].get_attribute('textContent')
    elif len(phones) == 1:
        gh = phones[0].get_attribute('textContent')
        phone = ''
    else:
        return ''
    print(name,namer,jyfw,address,phone,gh)
    print('===='*40)
    dictCookies = driver.get_cookies()  # 获取list的cookies
    jsonCookies = json.dumps(dictCookies)  # 转换成字符串保存
    with open('damai_cookies.txt', 'w') as f:
        f.write(jsonCookies)


if __name__ == '__main__':
    selenium_hw()
    # pool = Pool(2)
    # for i in range(0,1000,2):
    #     pool.apply_async(selenium_hw,(i,))
    # pool.close()
    # pool.join()

# 无信息数据--补充数据
